package com.mav.service.iml;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mav.mapper.ClazzMapper;
import com.mav.pojo.Clazz;
import com.mav.pojo.ClazzQueryParam;
import com.mav.pojo.PageResult;
import com.mav.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceIml implements ClazzService {
    @Autowired
    ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzlist = clazzMapper.list(clazzQueryParam.getName(), clazzQueryParam.getBegin(), clazzQueryParam.getEnd());
        LocalDate localDate = LocalDate.now();
        clazzlist.forEach(clazz -> {
            if (localDate.isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else if (localDate.isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开班");
            }else {
                clazz.setStatus("在读中");
            }
        });
        Page<Clazz> page = (Page<Clazz>) clazzlist;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public List<Clazz> findAllClazz() {
        return clazzMapper.findAll();
    }

    @Override
    public void deleteById(Integer id) throws DeleteException {
        Long total = clazzMapper.findClazzStudents(id);
        if(total==0){
            clazzMapper.deleteById(id);
        }else throw new DeleteException("班级下有学员,不能直接删除~");

    }

    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateById(clazz);
    }
}
